package System;


import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-02-03
 * Time: 02:17
 */
public class BorrowOperation implements IOperation{
    public void work() throws SQLException {
        System.out.println("借阅图书!");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入借阅的书名");
        String name = scanner.nextLine();

        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/BookControlSystem?characterEncoding=utf8&useSSL=False");
        dataSource.setUser("root");
        dataSource.setPassword("123456");

        Connection connection = dataSource.getConnection();

        String sql = "select * from BookList";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            String name2 = resultSet.getString(1);
            if(name2.equals(name)){
                String sql2 = "update BookList set isBorrowed = (?) where name = (?)";
                PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                preparedStatement2.setString(1,"已借阅");
                preparedStatement2.setString(2,name);
                preparedStatement2.executeUpdate();
                System.out.println("借阅成功");
                resultSet.close();
                connection.close();
                return;
            }
        }
        System.out.println("没有你要借阅的图书");

        resultSet.close();
        connection.close();
    }
}
